#!/usr/bin/env ruby

require 'Xml'
require 'Activity'
require 'DataObject'


class Mediator < Xml
  ACTIVITY = { :action => "action" }
  
  
  def activity_collect(node)
    act = Activity.new
    act.name = node.xpath("#{node.parent.path}/@name")[0].value
    act.type = node.xpath("#{node.parent.path}/@executionType")[0].value
    begin
      act.reference = node.xpath("#{node.path}//@reference")[0].value
    rescue
    end
    begin
      act.operation = node.xpath("#{node.path}//@operation")[0].value
    rescue
    end
    begin
      act.input = variables_input(node)
    rescue
    end
    begin
      act.output = variables_output(node)
    rescue
    end
    act.description
    act
  end

  def activities
    activities_doc.collect do |el|
      activity_collect el
    end
  end

  def activities_doc
    doc.xpath('//*').collect do |el|
      if ACTIVITY.has_value? el.name
	el
      end
    end.compact
  end

  def variables_project
    Xml.new(path.split("/")[0...-2].join("/")+"/default.bpmn").doc.xpath("//xmlns:dataObject")
  end

  def variable_to_data(node)
      var = DataObject.new
      var.name = node
      var.type = ""
      var.namespace = ""
      var.resource_type = ""
      var.description = ""
      var
  end

  def variables_input(node)
    var=[]
    node.xpath("#{node.path}//@expression").each do |f|
      variables_names_from_text(f.text).each do |name|
	if var.select{|v| v.name == name[0]}.size == 0
	  var << variable_by_name(name[0]) 
	end
      end
    end
    var.uniq.compact
  end

  def variables_output(node)
    var=[]
    node.xpath("#{node.path}//@target").each do |f|
      variables_names_from_text(f.text).each do |name|
	if var.select{|v| v.name == name[0]}.size == 0
	  var << variable_by_name(name[0]) 
	end
      end
    end
    var.uniq.compact
  end

  def variable_by_name(name)
    variable_to_data(name)
  end

  def variables_names_from_text(text)
    text.scan(/\$([\w.]+)/)
  end

  def type
    MEDIATOR
  end

end

